package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.IdentityManagement;
import com.ruoyi.system.service.IIdentityManagementService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 四级联考身份验证Controller
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@RestController
@RequestMapping("/system/identity")
public class IdentityManagementController extends BaseController
{
    @Autowired
    private IIdentityManagementService identityManagementService;


    /**
     * 读取 count.txt 文件内容并返回给前端，并且每调用一次该接口count.txt中的数值增加1写回count.txt
     */
    @GetMapping("/getTitle")
    public AjaxResult getTitle() {
        String countPath = RuoYiConfig.getProfile()+ "\\count.txt";
        String titlePath = RuoYiConfig.getProfile()+ "\\title.txt";

        try {
            String countcontent = new String(Files.readAllBytes(Paths.get(countPath)));
            String titlecontent = new String(Files.readAllBytes(Paths.get(titlePath)));

            int count = Integer.parseInt(countcontent.trim());

            Map<String, Object> result = new HashMap<>();
            result.put("content", titlecontent);
            String formattedCounter = String.format("%04d", count);
            result.put("count", "LN"+formattedCounter);

            count = count + 1;
            // 确保写回文件时使用正确的路径
            Files.write(Paths.get(countPath), String.valueOf(count).getBytes());
            return success(result);
        } catch (IOException e) {
            return error("读取文件失败: " + e.getMessage());
        }
    }

    /**
     * 查询四级联考身份验证列表
     */
    @PreAuthorize("@ss.hasPermi('system:identity:list')")
    @GetMapping("/list")
    public TableDataInfo list(IdentityManagement identityManagement)
    {
        startPage();
        List<IdentityManagement> list = identityManagementService.selectIdentityManagementList(identityManagement);
        return getDataTable(list);
    }

    /**
     * 导出四级联考身份验证列表
     */
    @PreAuthorize("@ss.hasPermi('system:identity:export')")
    @Log(title = "四级联考身份验证", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IdentityManagement identityManagement)
    {
        List<IdentityManagement> list = identityManagementService.selectIdentityManagementList(identityManagement);
        ExcelUtil<IdentityManagement> util = new ExcelUtil<IdentityManagement>(IdentityManagement.class);
        util.exportExcel(response, list, "四级联考身份验证数据");
    }

    /**
     * 获取四级联考身份验证详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:identity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(identityManagementService.selectIdentityManagementById(id));
    }

    /**
     * 新增四级联考身份验证
     */
    @PreAuthorize("@ss.hasPermi('system:identity:add')")
    @Log(title = "四级联考身份验证", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IdentityManagement identityManagement)
    {
        return toAjax(identityManagementService.insertIdentityManagement(identityManagement));
    }

    /**
     * 修改四级联考身份验证
     */
    @PreAuthorize("@ss.hasPermi('system:identity:edit')")
    @Log(title = "四级联考身份验证", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IdentityManagement identityManagement)
    {
        return toAjax(identityManagementService.updateIdentityManagement(identityManagement));
    }

    /**
     * 删除四级联考身份验证
     */
    @PreAuthorize("@ss.hasPermi('system:identity:remove')")
    @Log(title = "四级联考身份验证", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(identityManagementService.deleteIdentityManagementByIds(ids));
    }

    /**
     * 获取导入模板
     */
    @PreAuthorize("@ss.hasPermi('system:identity:import')")
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<IdentityManagement> util = new ExcelUtil<IdentityManagement>(IdentityManagement.class);
        util.importTemplateExcel(response, "四级联考身份验证数据");
    }

    /**
     * 导入四级联考身份验证数据
     */
    @PreAuthorize("@ss.hasPermi('system:identity:import')")
    @Log(title = "四级联考身份验证", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<IdentityManagement> util = new ExcelUtil<IdentityManagement>(IdentityManagement.class);
        List<IdentityManagement> identityList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = identityManagementService.importIdentityData(identityList, updateSupport, operName);
        return success(message);
    }
    
    /**
     * 生成递补身份验证名单
     */
    @PreAuthorize("@ss.hasPermi('system:identity:edit')")
    @Log(title = "生成递补身份验证名单", businessType = BusinessType.UPDATE)
    @PostMapping("/generateDbIdentityList")
    public AjaxResult generateDbIdentityList()
    {
        String operName = getUsername();
        int count = identityManagementService.generateDbIdentityList(operName);
        return success("成功生成递补身份验证名单，从成绩合格名单中递补" + count + "人");
    }

    /**
     * 获取四级联考身份验证统计数据
     */
    @PreAuthorize("@ss.hasPermi('system:identity:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        return success(identityManagementService.getIdentityStatistics());
    }
}
